<?php

namespace app\admin\controller\god;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Validate;

class Examarea extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model("Examarea");
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $result = ['total' => 0, 'rows' => []];
            $total = $this->model->count();
            if (intval($total) > 0) {
                $result['total'] = $total;
                $result['rows'] = $this->model->select();
            }

            return json($result);
        }

        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $args = $this->request->post("row/a");
            if (empty($args)) {
                $this->error('参数不能为空');
            }
            if (empty($args['name'])) {
                $this->error('考区名称不能为空');
            }
            if (empty($args['code'])) {
                $this->error('考区编号不能为空');
            }
            $save = $this->model->data([
                'name' => $args['name'],
                'code' => $args['code'],
                'is_choose' => $args['is_choose'],
                'area_id' => $args['area_id'],
                'status' => $args['status']
            ])->save();
            if (empty($save)) {
                $this->error('新增失败');
            }
            $this->success('操作成功');
        }

        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (empty($row)) {
            $this->error('参数异常');
        }
        if ($this->request->isPost()) {
            $this->token();
            $args = $this->request->post("row/a");
            if (empty($args)) {
                $this->error('参数错误');
            }
            $data = [
                'name' => $args['name'],
                'code' => $args['code'],
                'is_choose' => $args['is_choose'],
                'area_id' => $args['area_id'],
                'status' => $args['status']
            ];
            $save = $this->model->save($data, ['id' => intval($ids)]);
            if (empty($save)) {
                $this->error('更新失败');
            }
            $this->success('更新成功');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}